#include "activity_category_view.h"
#include "ui_activity_category_view.h"

#include "activity_list_view.h"

#include <QtDebug>

ActivityCategoryView::ActivityCategoryView(QWidget *parent) :
    ViewBase(parent),
    ui(new Ui::ActivityCategoryView),
    listView_(0)
{
    ui->setupUi(this);
    QAction *backSoftkeyAction = new QAction(QString("Back"), this);
    backSoftkeyAction->setSoftKeyRole(QAction::NegativeSoftKey);
    QObject::connect(backSoftkeyAction, SIGNAL(triggered()),
                     this, SLOT(close()));
    addAction(backSoftkeyAction);

    connect(ui->lstActivityCategory, SIGNAL(itemActivated(QListWidgetItem*)),
            this, SLOT(showActivityList(QListWidgetItem*)));
}

ActivityCategoryView::~ActivityCategoryView()
{
    delete ui;
    if (listView_) {
      delete listView_;
    }
}

void ActivityCategoryView::IssueRequest() {
  RequestMethod request(this, QString("xml"), QString("Activities.getAllCategory"));

  activityCategories.clear();

  ui->lstActivityCategory->clear();

  if (handler_) {
    handler_->IssueRequest(request);
  }
}

int ActivityCategoryView::ProcessResult(RequestMethod &, QDomElement &e) {
  int re = parse_result(e);
  if (re == 0) {
    for (int i = 0; i < activityCategories.count(); ++i) {
      cate &c = activityCategories[i];
      ui->lstActivityCategory->addItem(c.cn_cate);
    }
  }
  return re;
}

int ActivityCategoryView::parse_result(QDomElement &e) {
  QDomNodeList list = e.childNodes();
  for (int i = 0; i < list.count(); ++i) {
    QDomElement n = list.at(i).toElement();
    if (n.nodeName() == QString("cate")) {
      cate c;
      parse_cate(n, c);
      activityCategories.push_back(c);
    }
  }

  return 0;
}

void ActivityCategoryView::showActivityList(QListWidgetItem *item) {
  qDebug() << item->text();
  for (int i = 0; i < activityCategories.count(); ++i) {
    cate &c = activityCategories[i];
    if (c.cn_cate == item->text()) {
      if (!listView_) {
        listView_ = new ActivityListView(this);
        listView_->SetRequestHandler(handler_);
      }

      listView_->SetCategory(c);

      listView_->Show();
      listView_->IssueRequest();

      return;
    }
  }
}
